from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.core.paginator import Paginator
from django.db.models import Q
from .models import College
from .decorators import admin_required
from django import forms


class CollegeForm(forms.ModelForm):
    """学院表单"""
    class Meta:
        model = College
        fields = ['name', 'code', 'department', 'description']
        widgets = {
            'name': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入学院名称',
                'required': True
            }),
            'code': forms.TextInput(attrs={
                'class': 'form-control',
                'placeholder': '请输入学院代码',
                'required': True
            }),
            'department': forms.Select(attrs={
                'class': 'form-control',
                'required': True
            }),
            'description': forms.Textarea(attrs={
                'class': 'form-control',
                'rows': 4,
                'placeholder': '请输入学院描述'
            }),
        }
        labels = {
            'name': '学院名称',
            'code': '学院代码',
            'department': '所属学部',
            'description': '学院描述',
        }


@login_required
@admin_required
def college_list(request):
    """学院列表"""
    search = request.GET.get('search', '')
    colleges = College.objects.all()
    
    if search:
        colleges = colleges.filter(
            Q(name__icontains=search) | 
            Q(code__icontains=search) |
            Q(description__icontains=search)
        )
    
    colleges = colleges.order_by('name')
    
    # 分页
    paginator = Paginator(colleges, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'search': search,
        'total_count': colleges.count(),
    }
    return render(request, 'accounts/college_list.html', context)


@login_required
@admin_required
def college_create(request):
    """创建学院"""
    if request.method == 'POST':
        form = CollegeForm(request.POST)
        if form.is_valid():
            college = form.save()
            messages.success(request, f'学院 "{college.name}" 创建成功！')
            return redirect('accounts:college_list')
    else:
        form = CollegeForm()
    
    context = {
        'form': form,
        'title': '创建学院',
        'action': '创建',
    }
    return render(request, 'accounts/college_form.html', context)


@login_required
@admin_required
def college_update(request, pk):
    """更新学院"""
    college = get_object_or_404(College, pk=pk)
    
    if request.method == 'POST':
        form = CollegeForm(request.POST, instance=college)
        if form.is_valid():
            college = form.save()
            messages.success(request, f'学院 "{college.name}" 更新成功！')
            return redirect('accounts:college_list')
    else:
        form = CollegeForm(instance=college)
    
    context = {
        'form': form,
        'college': college,
        'title': f'编辑学院 - {college.name}',
        'action': '更新',
    }
    return render(request, 'accounts/college_form.html', context)


@login_required
@admin_required
def college_delete(request, pk):
    """删除学院"""
    college = get_object_or_404(College, pk=pk)
    
    if request.method == 'POST':
        # 检查是否有关联的用户或子项目
        user_count = college.userprofile_set.count()
        subproject_count = college.subproject_set.count()
        
        if user_count > 0 or subproject_count > 0:
            messages.error(
                request, 
                f'无法删除学院 "{college.name}"，因为还有 {user_count} 个用户和 {subproject_count} 个子项目关联到此学院。'
            )
            return redirect('accounts:college_list')
        
        college_name = college.name
        college.delete()
        messages.success(request, f'学院 "{college_name}" 删除成功！')
        return redirect('accounts:college_list')
    
    # 获取关联信息
    user_count = college.userprofile_set.count()
    subproject_count = college.subproject_set.count()
    
    context = {
        'college': college,
        'user_count': user_count,
        'subproject_count': subproject_count,
        'can_delete': user_count == 0 and subproject_count == 0,
    }
    return render(request, 'accounts/college_confirm_delete.html', context)


@login_required
@admin_required
def college_detail(request, pk):
    """学院详情"""
    college = get_object_or_404(College, pk=pk)
    
    # 获取关联的用户
    users = college.userprofile_set.select_related('user').all()
    
    # 获取关联的子项目
    subprojects = college.subproject_set.select_related('project').all()
    
    context = {
        'college': college,
        'users': users,
        'subprojects': subprojects,
        'user_count': users.count(),
        'subproject_count': subprojects.count(),
    }
    return render(request, 'accounts/college_detail.html', context)